<template>
    <a-spin :spinning="spinning" :tip="'加载中'" :delay="300">
        <div class="main_left_article">
            <div v-for="(item,index) in articleList" :key="item.id">
                <div v-if="item.type===1" class="main_left_article_item">
                    <router-link :to="{
            path: '/articleDetails',
            query: {
              articleId:item.id
            }
          }">
                        <div class="main_left_article_item_title" v-dompurify-html="item.title"></div>
                    </router-link>

                    <div class="main_left_article_item_label">
                        <div v-for="(item2,index) in item.labels" :key="index">
                            <a-button @click="labelSearch(item2)"
                                      v-dompurify-html="item2"
                                      class="main_left_article_item_label_item"
                                      type="primary" size="small"
                                      ghost></a-button>
                        </div>
                    </div>
                    <div class="main_left_article_item_3">
                        <div class="main_left_article_item_3_type">{{ item.gradeTranslation }}</div>
                        <div class="main_left_article_item_3_author">{{ item.user.nickname }}</div>
                    </div>
                    <div class="main_left_article_item_count">
                        <img class="main_left_article_item_count_img_1" src="@/assets/img/article/浏览.png" alt="浏览">
                        <div class="main_left_article_item_count_num">{{ item.views }}</div>
                        <img @click="handleUserGiveALike(item.id,index)" v-if="item.isLike===1"
                             class="main_left_article_item_count_img_2"
                             src="@/assets/img/article/点赞.png" alt="点赞">
                        <img @click="handleUserGiveALike(item.id,index)" v-else
                             class="main_left_article_item_count_img_2"
                             src="@/assets/img/article/未点赞.png" alt="未点赞">
                        <div class="main_left_article_item_count_num">{{ item.likeCount }}</div>
                        <img @click="handleUserCollect(item.id,index)" v-if="item.isCollect===1"
                             class="main_left_article_item_count_img_3"
                             src="@/assets/img/article/收藏.png" alt="收藏">
                        <img @click="handleUserCollect(item.id,index)" v-else
                             class="main_left_article_item_count_img_3"
                             src="@/assets/img/article/未收藏.png" alt="未收藏">
                        <div class="main_left_article_item_count_num">{{ item.collectCount }}</div>
                        <img class="main_left_article_item_count_img_4" src="@/assets/img/article/评论.png" alt="评论">
                        <div class="main_left_article_item_count_num">{{ item.commentCount }}</div>
                    </div>
                </div>
            </div>
            <a-pagination v-model:current="pagination.current"
                          v-model:page-size="pagination.pageSize"
                          :size="pagination.size"
                          :total="pagination.total"
                          :show-total="pagination.showTotal"
                          :show-size-changer="pagination.showSizeChanger"
                          @showSizeChange="pagination.onShowSizeChange"
                          @change="pagination.onChange"
                          show-quick-jumper
                          style="text-align: center;margin: 20px;padding-bottom: 10px"
            />
        </div>
    </a-spin>
</template>

<script setup lang="ts">
import {onMounted, ref} from "vue";
import {
    getUserCollectList,
    getUserGiveALikeList,
    saveUserCollect,
    saveUserGiveALike, searchArticle
} from "@/api/home/article";
import {Article, Collect, GiveALike} from "@/model/home/article";
// @ts-ignore
import cookie from 'js-cookie'
import {checkUserLogin} from "@/utils/getUser";
import {message} from "ant-design-vue";
import {useRouter} from "vue-router";
// @ts-ignore
import Publish from 'pubsub-js'
import {RequestParams} from "@/model/home/answer";
import {useStore} from "@/store";

const router = useRouter()

//是否显示加载中
const spinning = ref<boolean>(true);

//文章列表
const articleList = ref<Article[]>([])

//获取文章列表
const handleArticleList = async () => {
    if (requestParams.value.key == null) {
        requestParams.value.key = cookie.get("key")
    }
    requestParams.value.sortBy = 'id'
    const res = await searchArticle(requestParams.value)
    cookie.remove("key")
    articleList.value = res.data.data.pageResult.articles
    articleList.value.map(item => {
        item.labels = item.labelTranslation.split(",")
    })
    pagination.value.total = res.data.data.pageResult.total
    //查询当前用户的点赞记录
    await handleUserGiveALikeList()
    //查询当前用户的收藏记录
    await handleUserCollectList()
    setTimeout(async () => {
        spinning.value = false
    }, 1000)
}

//全文检索所需的参数
const requestParams = ref<RequestParams>({
    key: '',
    page: 1,
    size: 10,
    sortBy: ''
})

//接收全文检索的数据
const receiveSearchArticleList = () => {
    Publish.unsubscribe('searchArticleList')
    Publish.subscribe('searchArticleList', (functionName: string, message: any, c: any) => {
        //移除导航标签激活样式
        cookie.remove('isActive')
        //移除搜索参数
        cookie.remove("key")
        articleList.value = message[0]
        articleList.value.map(item => {
            item.labels = item.labelTranslation.split(",")
        })
        requestParams.value.key = message[1]
        pagination.value.total = message[2]
        handleUserGiveALikeList()
        handleUserCollectList()
    })
}

//接收头部组件传过来的搜索关键词
const receiveHeaderSearchKey = () => {
    Publish.subscribe('receiveHeaderSearchKey', (functionName: string, message: any, c: any) => {
        requestParams.value.key = message
        searchArticle(requestParams.value).then((res) => {
            res.data.data.pageResult.articles.map((item: any) => {
                item.title = item.title.replaceAll("<em>", "<nobr style='color: red;white-space: nowrap;'>")
                item.title = item.title.replaceAll("</em>", "</nobr>")
                item.labelTranslation = item.labelTranslation.replaceAll("<em>", "<nobr style='color: red;white-space: nowrap;'>")
                item.labelTranslation = item.labelTranslation.replaceAll("</em>", "</nobr>")
            })
            const store = useStore()
            store.setKey(requestParams.value.key)
            const msg = []
            msg.push(res.data.data.pageResult.articles)
            msg.push(requestParams.value.key)
            msg.push(res.data.data.pageResult.total)
            Publish.publish('searchArticleList', msg)
            router.push('/')
        })
    })
}

//接收其他页面传过来的标签
const receiveTagName = () => {
    Publish.subscribe('receiveTagName', (functionName: string, message: any, c: any) => {
        labelSearch(message)
    })
}

//标签搜索
const labelSearch = (tagName: string) => {
    requestParams.value.key = tagName
    searchArticle(requestParams.value).then((res) => {
        res.data.data.pageResult.articles.map((item: any) => {
            item.title = item.title.replaceAll("<em>", "<nobr style='color: red;white-space: nowrap;'>")
            item.title = item.title.replaceAll("</em>", "</nobr>")
            item.labelTranslation = item.labelTranslation.replaceAll("<em>", "<nobr style='color: red;white-space: nowrap;'>")
            item.labelTranslation = item.labelTranslation.replaceAll("</em>", "</nobr>")
        })
        const store = useStore()
        store.setKey(requestParams.value.key)
        const msg = []
        msg.push(res.data.data.pageResult.articles)
        msg.push(requestParams.value.key)
        msg.push(res.data.data.pageResult.total)
        Publish.publish('searchArticleList', msg)
        router.push('/')
    })
}

//分页
const pagination = ref({
    size: 'large',
    current: 1,
    pageSize: 10,
    total: 0,
    showTotal: (total: number) => {
        return " 共" + total + "条"
    },
    showSizeChanger: false,
    onShowSizeChange: (current: number, pageSize: number) => {
        pagination.value.pageSize = pageSize
        requestParams.value.size = pageSize
        searchArticle(requestParams.value).then((res) => {
            res.data.data.pageResult.articles.map((item: any) => {
                item.title = item.title.replaceAll("<em>", "<nobr style='color: red;white-space: nowrap;'>")
                item.title = item.title.replaceAll("</em>", "</nobr>")
                item.labelTranslation = item.labelTranslation.replaceAll("<em>", "<nobr style='color: red;white-space: nowrap;'>")
                item.labelTranslation = item.labelTranslation.replaceAll("</em>", "</nobr>")
            })
            const store = useStore()
            store.setKey(requestParams.value.key)
            const msg = []
            msg.push(res.data.data.pageResult.articles)
            msg.push(requestParams.value.key)
            msg.push(res.data.data.pageResult.total)
            Publish.publish('searchArticleList', msg)
            router.push('/')
        })
    },
    onChange: (current: number) => {
        pagination.value.current = current
        requestParams.value.page = current
        searchArticle(requestParams.value).then((res) => {
            res.data.data.pageResult.articles.map((item: any) => {
                item.title = item.title.replaceAll("<em>", "<nobr style='color: red;white-space: nowrap;'>")
                item.title = item.title.replaceAll("</em>", "</nobr>")
                item.labelTranslation = item.labelTranslation.replaceAll("<em>", "<nobr style='color: red;white-space: nowrap;'>")
                item.labelTranslation = item.labelTranslation.replaceAll("</em>", "</nobr>")
            })
            const store = useStore()
            store.setKey(requestParams.value.key)
            const msg = []
            msg.push(res.data.data.pageResult.articles)
            msg.push(requestParams.value.key)
            msg.push(res.data.data.pageResult.total)
            Publish.publish('searchArticleList', msg)
            router.push('/')
        })
    }
})

//用户点赞列表
const giveALikeList = ref()

//点赞所需的参数
const giveALike = ref<GiveALike>({
    articleId: 0,
    userId: 0
})

//判断当前用户是否点赞
const userIsGiveALike = () => {
    for (let i = 0; i < articleList.value.length; i++) {
        for (let j = 0; j < giveALikeList.value.length; j++) {
            if (articleList.value[i].id === giveALikeList.value[j].articleId) {
                articleList.value[i].isLike = giveALikeList.value[j].isLike
                break;
            } else {
                articleList.value[i].isLike = 0
            }
        }
    }
}

//查询当前用户的点赞记录
const handleUserGiveALikeList = async () => {
    const res = await getUserGiveALikeList(giveALike.value.userId)
    giveALikeList.value = res.data.data.list
    //判断当前用户是否点赞
    await userIsGiveALike()
}

//用户点赞
const handleUserGiveALike = async (articleId: number, index: number) => {
    giveALike.value.articleId = articleId
    if (!await checkUserLogin() || giveALike.value.userId === 0) {
        message.warn('未登录，无法点赞')
    } else {
        saveUserGiveALike(giveALike.value).then(() => {
            articleList.value[index].isLike = articleList.value[index].isLike === 1 ? 0 : 1
            //如果点赞，则点赞人数+1
            if (articleList.value[index].isLike === 1) {
                message.success("点赞成功")
                articleList.value[index].likeCount = articleList.value[index].likeCount + 1
            } else {
                message.warn("取消点赞")
                articleList.value[index].likeCount = articleList.value[index].likeCount - 1
            }
        })
    }
}

//用户收藏列表
const collectList = ref()

//收藏所需的参数
const collect = ref<Collect>({
    articleId: 0,
    userId: 0,
})

//判断当前用户是否收藏
const userIsCollect = () => {
    for (let i = 0; i < articleList.value.length; i++) {
        for (let j = 0; j < collectList.value.length; j++) {
            if (articleList.value[i].id === collectList.value[j].articleId) {
                articleList.value[i].isCollect = collectList.value[j].isCollect
                break;
            } else {
                articleList.value[i].isCollect = 0
            }
        }
    }
}

//查询当前用户的收藏记录
const handleUserCollectList = async () => {
    const res = await getUserCollectList(collect.value.userId)
    collectList.value = res.data.data.list
    await userIsCollect()
}

//用户收藏
const handleUserCollect = async (articleId: number, index: number) => {
    collect.value.articleId = articleId
    if (!await checkUserLogin() || collect.value.userId === 0) {
        message.warn('未登录，无法收藏')
    } else {
        saveUserCollect(collect.value).then(() => {
            articleList.value[index].isCollect = articleList.value[index].isCollect === 1 ? 0 : 1
            //如果收藏，则收藏人数+1
            if (articleList.value[index].isCollect === 1) {
                message.success("收藏成功")
                articleList.value[index].collectCount = articleList.value[index].collectCount + 1
            } else {
                message.warn("取消收藏")
                articleList.value[index].collectCount = articleList.value[index].collectCount - 1
            }
        })
    }
}

//从cookie中获取用户id
const getUserId = () => {
    if (cookie.get('userinfo') != null) {
        giveALike.value.userId = JSON.parse(cookie.get('userinfo')).id
        collect.value.userId = JSON.parse(cookie.get('userinfo')).id
    } else {
        giveALike.value.userId = 0
        collect.value.userId = 0
    }
}

getUserId()
handleArticleList()
onMounted(() => {
    receiveSearchArticleList()
    receiveTagName()
    receiveHeaderSearchKey()
})
</script>

<style lang="less" scoped>
.main_left_article {
  margin-top: 10px;
  background-color: #ffffff;

  .main_left_article_item_title {
    //display: flex;
    font-size: 20px;
    margin-bottom: 10px;
    margin-top: 10px;
    font-weight: bold;
    width: 95%;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    margin-left: 5px;
  }

  .main_left_article_item_title:hover {
    margin-left: 5px;
    color: red !important;
  }

  .main_left_article_item_label {
    margin-left: 5px;
    display: flex;

    .main_left_article_item_label_item {
      margin-right: 20px;
      display: flex;
    }
  }

  .main_left_article_item_3 {
    display: flex;
    margin-top: 10px;
    margin-left: 5px;

    .main_left_article_item_3_type {
      margin-right: 20px;
    }
  }

  .main_left_article_item_count {
    display: flex;
    margin-top: 10px;
    padding-bottom: 10px;
    border-bottom: 1px solid #f0f0f0;
    margin-left: 5px;

    .main_left_article_item_count_img_1 {
      width: 25px;
      height: 25px;
      margin-top: 1px;
      margin-right: 5px;
    }

    .main_left_article_item_count_img_2 {
      width: 25px;
      height: 25px;
      margin-right: 5px;
      cursor: pointer;
    }

    .main_left_article_item_count_img_3 {
      width: 25px;
      height: 25px;
      margin-right: 5px;
      cursor: pointer;
    }

    .main_left_article_item_count_img_4 {
      width: 25px;
      height: 25px;
      margin-right: 5px;
      cursor: pointer;
    }

    .main_left_article_item_count_num {
      margin-right: 50px;
    }
  }
}
</style>